import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { createAdaptorServer } from '@hono/node-server'
import sequelize from './ormconfig'
import container from './container'
import { setCron } from '../system/cron'
import { asValue } from 'awilix'
import config from './config'

function router(params){
  const [ controller, method ] = params
  return controller[method].bind(controller)
}

function register(server){
  container.register({
    conf: asValue(server.conf),
    server: asValue(server),
    sequelize: asValue(sequelize)
  })
}

class Server {
  constructor(port, conf) {
    this.port = port;
    this.conf = conf
    this.container = container
    
    register(this)
    
    this.app = new Hono()
    this.app.use(cors())

    this.app.use(async (c, next) => {
      c.container = container.createScope()
      await next()
    })

    // 初始化程序
    this.init()

    // 创建服务器
    this.server = createAdaptorServer({
      fetch: this.app.fetch,
    })
  }

  async init(){
    // 动态导入p-queue
    await this.setupPQueue();

    // 设置路由
    this.setupRoutes();

    // 开启定时任务 注意这个要先动态导入p-queue
    this.scheduledTasks();
  }

  async setupPQueue(){
    const PQueue = await import('p-queue').then(module => module.default);
    
    // 创建队列 并发数为 4
    const queue = new PQueue({concurrency: config.queue.concurrency});

    container.register({
      queue: asValue(queue)
    })

    this.queue = queue
  }

  // 开启定时任务
  scheduledTasks(){
    // 每分钟的第17秒触发
    setCron('17 * * * * *', () => {
      this.container.resolve('filmMultimediaRelationJob').execute()
    });
  }

  // 设置路由
  setupRoutes(){
    // 首页
    this.app.get('/', router([this.container.resolve('indexController'), 'index']))

    // 首页
    this.app.get('/ffmpeg/test', router([this.container.resolve('indexController'), 'ffmpeg']))

    // 代理请求
    this.app.all(`/api/:path{.*}`, router([this.container.resolve('proxyController'), 'proxy']))

    // 配置
    this.app.get('/api/public/system/config', router([this.container.resolve('systemController'), 'getConfig']))

    // 获取用户信息
    this.app.get('/api/work_ai/user/info', router([this.container.resolve('userController'), 'getUserInfo']))

    // 视频发布
    this.app.post('/api/work_ai/user/filmrelease/create', router([this.container.resolve('filmReleaseController'), 'qrRelease']))
    
    // 重新发布
    this.app.put('/api/work_ai/user/filmrelease/rePublish', router([this.container.resolve('filmReleaseController'), 'rePublish']))
  }

  // 启动服务器
  start() {
    return new Promise((resolve, reject) => {
      this.server.listen(this.port, () => {
        console.log(`Server is running on http://localhost:${this.port}`);
        resolve(true);
      }).on('error', reject)
    });
  }
}

export default Server;